//
//  ChooseMusicController.m
//  OnionHome
//
//  Created by fengjie on 2019/10/8.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "ChooseMusicController.h"
#import "FJAudioTool.h"

@interface ChooseMusicController ()
/**<#属性#>*/
@property (nonatomic,strong)UITextField*serachField;
/**<#属性#>*/
@property (nonatomic,strong)UITableViewTool*listViewTool;
/**<#属性#>*/
@property (nonatomic,strong)NSMutableArray*dataArray;
/**<#属性#>*/
@property (nonatomic,strong)ChooseMusicModel * currumodel;

/**<#属性#>*/
@property (nonatomic,strong)AVPlayer*audioPlayer;
/**<#属性#>*/
@property (nonatomic,strong)NSIndexPath*seleIndexPath;

@end

@implementation ChooseMusicController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择音乐";
    [self setSerachView];
    [self.listViewTool.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(44);
    }];
}
-(void)backBtnClicked{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 设置搜索栏
 */
-(void)setSerachView{
    UIView * view = [self createSerbar];
    
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
}
#pragma mark ---懒加载
-(UIView * )createSerbar{
    UIView * view = UIView.new;
    view.backgroundColor = UIColor.whiteColor;
    
    UIView * view1 = UIView.new;
    view1.backgroundColor = UIColorFromRGB(0xF5F7F5);
    ViewRadius(view1, 4);
    
    [view addSubview:view1];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(30);
    }];
    
    UIImageView * leftImage = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"ic_nav_search")];
    [view1 addSubview:leftImage];
    [view1 addSubview:self.serachField];
    

    [leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(8);
    }];
    
    [self.serachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(leftImage.mas_right).offset(4);
        make.top.bottom.mas_equalTo(0);
    }];
    
    
    return view;
}

-(UITextField*)serachField{
    if(!_serachField){
        _serachField=[UITextField new];
        _serachField.placeholder = @"热门搜索、热门搜索";
    }
    return _serachField;
}

-(UITableViewTool*)listViewTool{
    if(!_listViewTool){
        kWeakSelf(weakSelf);
        _listViewTool=[[UITableViewTool alloc] initWithFrame:CGRectZero style:UITableViewStylePlain registerCellClassName:NSStringFromClass([ChooseMusicCell class]) identifier:NSStringFromClass([ChooseMusicCell class]) dataArray:self.dataArray delegate:self dataSourceBlock:^(id  _Nonnull TempCell, NSIndexPath * _Nonnull indexPath, id  _Nonnull TempData) {
            ChooseMusicCell * cell = (ChooseMusicCell *)TempCell;
            cell.model = (ChooseMusicModel *)TempData;
            
            cell.payBlock = ^{
                [weakSelf playeMusicAction:indexPath];
            };
            
        } selectCell:^(id  _Nonnull TempCell, NSIndexPath * _Nonnull indexPath, id  _Nonnull TempData) {
            
        }];
        _listViewTool.listView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return _listViewTool;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray =[[NSMutableArray alloc] init];
        
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"musicList" ofType:@"json"]];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
        [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ChooseMusicModel *model = [ChooseMusicModel new];
            [model setValuesForKeysWithDictionary:obj];
            [_dataArray addObject:model];
        }];

    }
    return _dataArray;
}
-(void)playeMusicAction:(NSIndexPath *)indexpath{
    if (self.seleIndexPath) {
        ChooseMusicModel * seleModel = self.dataArray[self.seleIndexPath.row];
        seleModel.isPlay = !seleModel.isPlay;
        self.dataArray[self.seleIndexPath.row] = seleModel;
    }
    self.seleIndexPath = indexpath;
    ChooseMusicModel * model = self.dataArray[indexpath.row];
    model.isPlay = !model.isPlay;
    self.dataArray[indexpath.row] = model;
    [self.listViewTool reloadData:self.dataArray];
    
    if (self.audioPlayer) {
        self.audioPlayer = nil;
    }
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:model.musicPlayUrl] options:nil];
    AVPlayerItem *songitem = [[AVPlayerItem alloc] initWithAsset:asset];
    self.audioPlayer = [[AVPlayer alloc] initWithPlayerItem:songitem];
    
    [songitem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

    [self.audioPlayer play];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        //AVPlayerItemStatus *status = item.status;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            [self.audioPlayer play];
            //对播放界面的一些操作，时间、进度等
        }
    }
}
-(void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    
}
@end



@interface ChooseMusicCell ()

/**<#属性#>*/
@property (nonatomic,strong)UIImageView*leftImage;
/**<#属性#>*/
@property (nonatomic,strong)UILabel*topLabel;
/**<#属性#>*/
@property (nonatomic,strong)UILabel*bomLable;
/**<#属性#>*/
@property (nonatomic,strong)UILabel*rightLabel;

/**<#属性#>*/
@property (nonatomic,strong)UIButton*playBtn;

@end

@implementation ChooseMusicCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self createUI];
    }
    return self;
}
-(void)setModel:(ChooseMusicModel *)model{
    _model = model;
    [self.leftImage imageViewWithUrl:model.pictureUrl placeholderImage:@"dynamicDefut"];
    self.topLabel.text = model.musicName;
    self.bomLable.text = model.singer;
    self.playBtn.selected = model.isPlay;
}
-(void)createUI{
    [self addSubview:self.leftImage];
    [self addSubview:self.topLabel];
    [self addSubview:self.bomLable];
    [self addSubview:self.rightLabel];
    
    [self.leftImage addSubview:self.playBtn];
    
    [self.leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(16);
        make.bottom.mas_equalTo(-16);
        make.width.height.mas_equalTo(64);
    }];
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.leftImage.mas_right).offset(20);
        make.top.mas_equalTo(self.leftImage.mas_top).offset(10);
    }];
    [self.bomLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topLabel);
        make.top.mas_equalTo(self.topLabel.mas_bottom).offset(5);
    }];
    
    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.centerY.mas_equalTo(0);
    }];
    
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
}

-(UIImageView*)leftImage{
    if(!_leftImage){
        _leftImage=[UIImageView new];
        ViewRadius(_leftImage, 32);
        _leftImage.image = IMAGE_NAMED(@"userIconDefut");
        _leftImage.userInteractionEnabled = YES;
    }
    return _leftImage;
}
-(UIButton*)playBtn{
    if(!_playBtn){
        _playBtn=[UIButton new];
        [_playBtn setBackgroundImage:IMAGE_NAMED(@"xiao_video_play") forState:UIControlStateNormal];
        [_playBtn setBackgroundImage:IMAGE_NAMED(@"CLPauseBtn") forState:UIControlStateSelected];
        kWeakSelf(weakSelf);
        [_playBtn addActionHandler:^{
            weakSelf.playBtn.selected = !weakSelf.playBtn.selected;
            BlockSafeRun(weakSelf.payBlock);
        }];
    }
    return _playBtn;
}
-(UILabel*)topLabel{
    if(!_topLabel){
        _topLabel=[UILabel new];
        _topLabel.text = @"等你下课";
        _topLabel.font = PingFangSC_Medium(16);
        _topLabel.textColor = KBlackColor;
    }
    return _topLabel;
}
-(UILabel*)bomLable{
    if(!_bomLable){
        _bomLable=[UILabel new];
        _bomLable.text = @"周杰伦";
        _bomLable.font = SYSTEMFONT(12);
        _bomLable.textColor = UIColorFromRGB(0x959E97);
    }
    return _bomLable;
}
-(UILabel*)rightLabel{
    if(!_rightLabel){
        _rightLabel=[UILabel new];
        _rightLabel.text = @"00:07";
        _rightLabel.font = SYSTEMFONT(12);
        _rightLabel.textColor = UIColorFromRGB(0x959E97);
    }
    return _rightLabel;
}

@end



@implementation ChooseMusicModel



@end
